#include<ros/ros.h>
#include<tf/tf.h>
#include<Eigen/Dense>
#include<geometry_msgs/PointStamped.h>
#include<geometry_msgs/TransformStamped.h>
#include<geometry_msgs/PoseStamped.h>
#include<geometry_msgs/TwistStamped.h>
#include<geometry_msgs/Vector3Stamped.h>
#include<mavros_msgs/AttitudeTarget.h>
#include <mavros_msgs/CommandBool.h>
#include <mavros_msgs/SetMode.h>
#include <mavros_msgs/State.h>
#include<uav/ecbf_att.h>
//#include<uav/att_publish.h>
#include<visualization_msgs/Marker.h>
#include<nav_msgs/Path.h>
#include<sensor_msgs/Imu.h>

//上升结束
int flag_pos=0;
//计数
int count_all=0;
int count_out=0;
//全局变量
////控制量
mavros_msgs::AttitudeTarget acc_out;
geometry_msgs::PoseStamped pos_out;
////PID
Eigen::Vector3d kp,ki,kd;
////期望速度/位置
Eigen::Vector3d twist_cal,pos_cal;
////速度/位置误差
Eigen::Vector3d twist_err,pos_err;
////输入/经ECBF优化/再经PID输入/转换为油门
Eigen::Vector3d acc_in,acc_ecbf,acc_pid,acc_thro;
////油门到姿态控制=四元数+thrust
geometry_msgs::Quaternion q_out;
double thrust_out;
////积分项
Eigen::Vector3d integral;

double lat_time;//last_time是给marker的变量
double dt=0;

//自定义函数
////期望位置速度
void  state_cal(Eigen::Vector3d &pos_cal,Eigen::Vector3d &twt_cal,geometry_msgs::PoseStamped last_pos,geometry_msgs::TwistStamped last_twst,Eigen::Vector3d opt_acc,double dt);
////期望位置速度误差
void state_err(Eigen::Vector3d &err_pos,Eigen::Vector3d &err_vel,Eigen::Vector3d pos_cal,Eigen::Vector3d vel_cal,geometry_msgs::PoseStamped pos,geometry_msgs::TwistStamped twst);
////输出转换
void att_convert(mavros_msgs::AttitudeTarget &output,geometry_msgs::Quaternion input,double thrust_sp);
////ecbf优化
mavros_msgs::AttitudeTarget optimization(Eigen::Vector3d input,geometry_msgs::PoseStamped pose_,geometry_msgs::TwistStamped twst);
////判断UAV位置
int testPos(geometry_msgs::PoseStamped pos);
////acc->thrust->throttle
Eigen::Vector3d accel2throttle(Eigen::Vector3d accel);
////油门转姿态角
void  ThrottleToAttitude(geometry_msgs::Quaternion &desired_att_q,double &desired_throttle,const Eigen::Vector3d thr_sp, double yaw_sp);
////姿态角输出
void att_convert(mavros_msgs::AttitudeTarget &output,geometry_msgs::Quaternion input,double thrust_sp);
////串行式
void casOPT(Eigen::Vector3d &output,Eigen::Vector3d input);


//状态回调函数
mavros_msgs::State current_state;
void state_cb(const mavros_msgs::State::ConstPtr& msg){
    current_state = *msg;
}

//位置回调函数
geometry_msgs::PoseStamped current_pose,last_pose;
void pose_cb(const geometry_msgs::PoseStamped::ConstPtr &msg1)
{
    current_pose=*msg1; 
    tf::Quaternion temp;
    //double roll,pitch;
    //tf::quaternionMsgToTF(current_pose.pose.orientation,temp);
    //tf::Matrix3x3(temp).getRPY(roll,pitch,yaw_ref);
}

//速度回调函数
geometry_msgs::TwistStamped current_twist,last_twist;
void twist_cb(const geometry_msgs::TwistStamped::ConstPtr &msg2)
{
    current_twist= *msg2;
}

//姿态角回调函数
/* geometry_msgs::Quaternion current_q;
void att_cb(const sensor_msgs::Imu::ConstPtr& msg3)
{
    current_q.x=msg3->orientation.x;
    current_q.y=msg3->orientation.y;
    current_q.z=msg3->orientation.z;
    current_q.w=msg3->orientation.w;
} */


int main(int argc, char** argv)
{
    ros::init(argc,argv,"ecbf_node");
    ros::NodeHandle nh;


    //收发器
    ros::Subscriber state_sub = nh.subscribe<mavros_msgs::State>("mavros/state", 10, state_cb);
    ros::Subscriber local_vel=nh.subscribe<geometry_msgs::TwistStamped>("/mavros/local_position/velocity_local",10,twist_cb);
    ros::Subscriber local_pos=nh.subscribe<geometry_msgs::PoseStamped>("mavros/local_position/pose",10,pose_cb);
/*     ros::Subscriber local_att=nh.subscribe<sensor_msgs::Imu>("mavros/imu/data",10,att_cb); */

    ros::Publisher marker_pub=nh.advertise<visualization_msgs::Marker>("marker",10);
    ros::Publisher path_pub = nh.advertise<nav_msgs::Path>("trajectory", 10);
    ros::Publisher point_pub = nh.advertise<geometry_msgs::PointStamped>("point", 10);
    ros::Publisher pos_pub=nh.advertise<geometry_msgs::PoseStamped>("/mavros/setpoint_position/local",10);
    /* ros::Publisher att_pub=nh.advertise<mavros_msgs::PositionTarget>("mavros/setpoint_raw/local",10); */
    ros::Publisher att_pub=nh.advertise<mavros_msgs::AttitudeTarget>("/mavros/setpoint_raw/attitude",10);

    ros::ServiceClient arming_client = nh.serviceClient<mavros_msgs::CommandBool>
            ("mavros/cmd/arming");
    ros::ServiceClient set_mode_client = nh.serviceClient<mavros_msgs::SetMode>
            ("mavros/set_mode");

    //trajectory
    ros::Time current_time, last_time;
    current_time = ros::Time::now();
    last_time = ros::Time::now();

    nav_msgs::Path path;
    path.header.stamp = current_time;
    path.header.frame_id = "map";


    visualization_msgs::Marker box;
    box.header.frame_id="map";
    box.lifetime=ros::Duration(0);
    box.action=visualization_msgs::Marker::ADD;
    box.ns="cube";
    box.pose.orientation.w=1.0;
    box.id=2;
    box.type=visualization_msgs::Marker::CUBE;
    box.scale.x=3;
    box.scale.y=3;
    box.scale.z=1;
    box.pose.position.x=0;
    box.pose.position.y=0;
    box.pose.position.z=1.5;
    box.color.r = 1.0;
    box.color.a = 0.85;

    
    //边缘
    visualization_msgs::Marker line_list;
    line_list.header.frame_id="map";
    line_list.lifetime=ros::Duration(0);
    line_list.ns="lines";
    line_list.action = visualization_msgs::Marker::ADD;
    line_list.pose.orientation.w = 1.0;
    line_list.id = 2;
    line_list.type = visualization_msgs::Marker::LINE_LIST;
    line_list.scale.x = 0.01;
    line_list.scale.y=0.01;
    line_list.scale.z=0.01;

    // Line list is blue
    line_list.color.b = 1.0;
    line_list.color.a = 1;
    geometry_msgs::Point p1;
    p1.x=-1.5;
    p1.y=-1.5;
    p1.z=1;
    geometry_msgs::Point p2;
    p2.x=1.5;
    p2.y=-1.5;
    p2.z=1;
    geometry_msgs::Point p3;
    p3.x=1.5;
    p3.y=1.5;
    p3.z=1;
    geometry_msgs::Point p4;
    p4.x=-1.5;
    p4.y=1.5;
    p4.z=1;
    geometry_msgs::Point p5;
    p5.x=-1.5;
    p5.y=-1.5;
    p5.z=2;
    geometry_msgs::Point p6;
    p6.x=1.5;
    p6.y=-1.5;
    p6.z=2;
    geometry_msgs::Point p7;
    p7.x=1.5;
    p7.y=1.5;
    p7.z=2;
    geometry_msgs::Point p8;
    p8.x=-1.5;
    p8.y=1.5;
    p8.z=2;

    line_list.points.push_back(p1);
    line_list.points.push_back(p2);
    line_list.points.push_back(p2);
    line_list.points.push_back(p3);
    line_list.points.push_back(p3);
    line_list.points.push_back(p4);
    line_list.points.push_back(p4);
    line_list.points.push_back(p1);

    line_list.points.push_back(p5);
    line_list.points.push_back(p6);
    line_list.points.push_back(p6);
    line_list.points.push_back(p7);
    line_list.points.push_back(p7);
    line_list.points.push_back(p8);
    line_list.points.push_back(p8);
    line_list.points.push_back(p5);

    line_list.points.push_back(p1);
    line_list.points.push_back(p5);
    line_list.points.push_back(p2);
    line_list.points.push_back(p6);
    line_list.points.push_back(p3);
    line_list.points.push_back(p7);
    line_list.points.push_back(p4);
    line_list.points.push_back(p8);

    ros::Rate rate(20.0);

    while(ros::ok() && !current_state.connected)
    {
        ros::spinOnce();
        rate.sleep();
    }
    
    //位置控制
    pos_out.pose.position.x=0;
    pos_out.pose.position.y=0;
    pos_out.pose.position.z=1.5;

    //原始输入加速度与积分项初始化
    acc_in=Eigen::Vector3d(0,0,15);
    integral=Eigen::Vector3d(0,0,0);
    kp=Eigen::Vector3d(1,1,2);
    ki=Eigen::Vector3d(0.5,0.5,0.5);
    kd=Eigen::Vector3d(0.2,0.2,0.2);

    for(int i=100;ros::ok()&&i>0;--i)
    {
        pos_pub.publish(pos_out);
        ros::spinOnce();
        rate.sleep();
    }

    mavros_msgs::SetMode offb_set_mode;
    offb_set_mode.request.custom_mode = "OFFBOARD";
    mavros_msgs::CommandBool arm_cmd;
    arm_cmd.request.value = true;
    ros::Time last_request = ros::Time::now();

    while(ros::ok())
    {
        marker_pub.publish(line_list);
        line_list.header.stamp=ros::Time::now();
        marker_pub.publish(box);
        box.header.stamp=ros::Time::now();

        geometry_msgs::PointStamped this_point_stamped;
        this_point_stamped.header.stamp = current_time;
        this_point_stamped.header.frame_id = "map";
        this_point_stamped.point.x = current_pose.pose.position.x;
        this_point_stamped.point.y = current_pose.pose.position.y;
        this_point_stamped.point.z = current_pose.pose.position.z;

        point_pub.publish(this_point_stamped);

        if(current_state.mode!="OFFBOARD"&&
        (ros::Time::now()-last_request>ros::Duration(5.0)))
        {
            if(set_mode_client.call(offb_set_mode)&&
            offb_set_mode.response.mode_sent)
            {
                ROS_INFO("Offboard enabled");
            }
            last_request=ros::Time::now();
        }
        else
        {
            if(!current_state.armed&&
            (ros::Time::now()-last_request>ros::Duration(5.0)))
            {
                if(arming_client.call(arm_cmd)&&
                arm_cmd.response.success)
                {
                    ROS_INFO("Vehicle armed");
                }
                last_request=ros::Time::now();
            }
        }

        //spinOnce放在两次操作中
        if(flag_pos==0)
        {
            pos_pub.publish(pos_out);
            ros::spinOnce();
            rate.sleep();
            if(current_pose.pose.position.z>1.5)
            {
                lat_time=ros::Time::now().toSec();
                flag_pos=1;
            }
        } 
        if(flag_pos==1)
        { 
            ros::spinOnce();
            rate.sleep();
            double cur_time=ros::Time::now().toSec();
            dt=cur_time-lat_time;
            ROS_INFO("T=%f,%f",cur_time,dt);
            lat_time=cur_time;

            int flag=0;
            flag=testPos(current_pose);
            if(flag==3)
            {
                ROS_INFO("within the range");
            }
            if(flag==4)
            {
                ROS_INFO("out of range");
                count_out++;
            }
            count_all++;
            ROS_INFO("detected for %d times, out for %d times",count_all,count_out);

            //pose发布
            geometry_msgs::PoseStamped this_pose_stamped;
            this_pose_stamped=current_pose;
            this_pose_stamped.header.stamp = current_time;
            this_pose_stamped.header.frame_id = "base";
            path.poses.push_back(this_pose_stamped);
            path_pub.publish(path);
            last_time = current_time;

            //ecbf优化
            acc_out=optimization(acc_in,current_pose,current_twist);

            att_pub.publish(acc_out);

        } 
    }
    return 0;


}